package com.yanwq.sayhi.controller.article.adapter;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.ijkplayer.widget.media.IjkVideoView;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.common.client.MImageLoader;
import com.yanwq.sayhi.common.client.OkFileResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.tool.DateFormatTool;
import com.yanwq.sayhi.common.tool.MD5Tool;
import com.yanwq.sayhi.controller.article.activity.VideoPlayActivity;
import com.yanwq.sayhi.controller.audio.AudioPlayerWrap;
import com.yanwq.sayhi.controller.comment.activity.CommentListActivity;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.dao.bean.ArticleAttitude;
import com.yanwq.sayhi.widget.anim.AnimCompact;
import com.yanwq.sayhi.widget.anim.RecyclerWrapper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 作者：yanweiqiang。
 * 日期：2016/2/2 14:30。
 */
@SuppressWarnings("ALL")
public class ArticleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Article> mList;
    private AudioPlayerWrap mPlayer;
    private AnimCompact mAnimCompact;
    private RecyclerWrapper mRecyclerWrapper;

    private ExecutorService mExService;

    public ArticleAdapter() {
        mList = new ArrayList<>();
        mPlayer = new AudioPlayerWrap();
        mExService = Executors.newSingleThreadExecutor();

        mAnimCompact = new AnimCompact(new AnimCompact.CustomAnimators() {
            @Override
            public Animator[] animators(View view) {
                ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0, 1);
                alpha.setDuration(500);
                alpha.setInterpolator(new LinearInterpolator());
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", .8f, 1f);
                scaleX.setDuration(500);
                ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", .8f, 1f);
                scaleY.setDuration(500);
                ObjectAnimator translationY = ObjectAnimator.ofFloat(view, "translationY", view.getMeasuredHeight(), 0);
                translationY.setDuration(500);
                return new Animator[]{alpha, scaleX, scaleY};
            }
        });

        mAnimCompact.setStartPosition(0);
        mAnimCompact.setFirstOnly(false);
        mRecyclerWrapper = new RecyclerWrapper();
    }

    public void refresh(List<Article> list) {
        mList.clear();
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void load(List<Article> list) {
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void addHeader(View headerView) {
        mRecyclerWrapper.addHeader(headerView);
    }

    public void addFooter(View footerView) {
        mRecyclerWrapper.addFooter(footerView);
    }

    @Override
    public int getItemCount() {
        return mRecyclerWrapper.getItemCount(mList.size());
    }

    @Override
    public int getItemViewType(int position) {
        int type = mRecyclerWrapper.getItemViewType(position, mList.size());

        if (type == -1) {
            return mList.get(mRecyclerWrapper.getOriginPosition(position)).getType();
        }

        return type;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case 0:
                return new TextHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article_text, parent, false));
            case 1:
                return new PhotoHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article_photo, parent, false));

            case 2:
                return new AudioHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article_audio, parent, false));

            case 3:
                return new VideoHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article_video, parent, false));
            default:
                return mRecyclerWrapper.onCreateViewHolder(viewType, mList.size());
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        position = mRecyclerWrapper.getOriginPosition(position);

        if (holder instanceof TextHolder) {
            getViewText((TextHolder) holder, position);
        } else if (holder instanceof PhotoHolder) {
            getViewPhoto((PhotoHolder) holder, position);
        } else if (holder instanceof AudioHolder) {
            getViewAudio((AudioHolder) holder, position);
        } else if (holder instanceof VideoHolder) {
            getViewVideo((VideoHolder) holder, position);
        }

        //mAnimCompact.onBindViewHolder(holder.itemView, position);
    }

    private RecyclerView.ViewHolder getViewText(TextHolder holder, final int position) {
        final Context context = holder.itemView.getContext();
        Article article = mList.get(position);
        userInfo(holder, article);

        holder.summary.setText(article.getSummary());
        holder.publishTime.setText(DateFormatTool.format(article.getPublishTime()));
        holder.text.setText(article.getText());

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Article article = mList.get(position);
                Intent intent = new Intent(context, CommentListActivity.class);
                intent.putExtra("article", article);
                context.startActivity(intent);
            }
        });
        return holder;
    }

    private void getViewPhoto(PhotoHolder holder, final int position) {
        final Context context = holder.itemView.getContext();
        Article article = mList.get(position);
        userInfo(holder, article);

        holder.summary.setText(article.getSummary());
        holder.publishTime.setText(DateFormatTool.format(article.getPublishTime()));
        MImageLoader.displayImage(article.getPhotoOriginUrl(), holder.photo);

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Article article = mList.get(position);
                Intent intent = new Intent(context, CommentListActivity.class);
                intent.putExtra("article", article);
                context.startActivity(intent);
            }
        });
    }

    private void getViewAudio(final AudioHolder holder, final int position) {
        final Context context = holder.itemView.getContext();
        final Article article = mList.get(position);
        userInfo(holder, article);

        holder.summary.setText(article.getSummary());
        holder.publishTime.setText(DateFormatTool.format(article.getPublishTime()));

        holder.audio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(article.getAudioUrl())) {
                    return;
                }

                holder.audio.setVisibility(View.GONE);
                holder.pb.setVisibility(View.VISIBLE);

                final File file = new File(CacheConstant.getRootPath(), String.format("%s.amr", MD5Tool.GetMD5Code(article.getAudioUrl())));
                OkRequestParams params = new OkRequestParams();

                OkRestClient.getInstance().getDirect(context,
                        article.getAudioUrl(),
                        params,
                        new OkFileResponseCallback(file) {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onStop() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                mPlayer.play(file.getAbsolutePath(),
                                        new MediaPlayer.OnCompletionListener() {
                                            @Override
                                            public void onCompletion(MediaPlayer mp) {
                                                holder.audio.setVisibility(View.VISIBLE);
                                                holder.pb.setVisibility(View.INVISIBLE);
                                            }
                                        });
                            }

                            @Override
                            public void onProgress(long currentLength, long totalLength) {

                            }
                        });
            }
        });

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Article article = mList.get(position);
                Intent intent = new Intent(context, CommentListActivity.class);
                intent.putExtra("article", article);
                context.startActivity(intent);
            }
        });
    }

    private void getViewVideo(final VideoHolder holder, final int position) {
        final Context context = holder.itemView.getContext();
        final Article article = mList.get(position);
        userInfo(holder, article);
        holder.summary.setText(article.getSummary());
        holder.publishTime.setText(DateFormatTool.format(article.getPublishTime()));
        MImageLoader.displayImage(article.getPhotoOriginUrl(), holder.photo);

        holder.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, VideoPlayActivity.class);
                intent.putExtra("path", article.getVideoUrl());
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation((Activity) context, holder.photo, "video");
                    context.startActivity(intent, options.toBundle());
                } else {
                    context.startActivity(intent);
                }
            }
        });

        holder.video.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer mp) {
                holder.play.setImageResource(R.drawable.ic_play_arrow_white_24dp);
                holder.play.setTag(null);
            }
        });

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Article article = mList.get(position);
                Intent intent = new Intent(context, CommentListActivity.class);
                intent.putExtra("article", article);
                context.startActivity(intent);
            }
        });
    }

    private void userInfo(final ViewHolder holder, final Article article) {
        final Context context = holder.itemView.getContext();
        if (article.getAttitude() == null) {
            ArticleAttitude attitude = new ArticleAttitude();
            attitude.setType(-1);
            attitude.setArticle(article);
            attitude.setUser(UserMgr.get());

            article.setAttitude(attitude);

            holder.laugh.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_up_48px), null, null, null);
            holder.cry.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_down_48px), null, null, null);
        } else {
            ArticleAttitude attitude = article.getAttitude();
            attitude.setArticle(article);
            attitude.setUser(UserMgr.get());

            if (attitude.getType() == 0) {
                holder.laugh.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_up_black_18dp), null, null, null);
                holder.cry.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_down_48px), null, null, null);
            } else if (attitude.getType() == 1) {
                holder.cry.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_down_black_18dp), null, null, null);
                holder.laugh.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_up_48px), null, null, null);
            }
        }

        MImageLoader.displayImage(article.getUser().getAvatarThumbUrl(), holder.avatar);
        holder.nickname.setText(article.getUser().getNickname());
        holder.laugh.setText(String.valueOf(article.getAttitude0Count()));
        holder.cry.setText(String.valueOf(article.getAttitude1Count()));
        holder.comment.setText(String.valueOf(article.getCommentCount()));

        if (article.getCommentCount() == 0) {
            holder.comment.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_mode_comment_48px), null, null, null);
        } else {
            holder.comment.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_mode_comment_black_18dp), null, null, null);
        }

        holder.laugh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (article.getAttitude().getType() == 0) {
                    return;
                }

                article.getAttitude().setType(0);
                article.setAttitude0Count(article.getAttitude0Count() + 1);
                article.setAttitude1Count(article.getAttitude1Count() - 1 < 0 ? 0 : article.getAttitude1Count() - 1);

                holder.laugh.setText(String.valueOf(article.getAttitude0Count()));
                holder.cry.setText(String.valueOf(article.getAttitude1Count()));

                holder.laugh.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_up_black_18dp), null, null, null);
                holder.cry.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_down_48px), null, null, null);

                mExService.submit(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = OkRestClient.getInstance().post("/article/attitude/add", article.getAttitude());
                        ArticleAttitude articleAttitude = JSON.toJavaObject(jsonObject, ArticleAttitude.class);
                        articleAttitude.setArticle(article.clone());
                        article.setAttitude(articleAttitude);
                    }
                });
            }
        });

        holder.cry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (article.getAttitude().getType() == 1) {
                    return;
                }

                article.getAttitude().setType(1);
                article.setAttitude0Count(article.getAttitude0Count() - 1 < 0 ? 0 : article.getAttitude0Count() - 1);
                article.setAttitude1Count(article.getAttitude1Count() + 1);

                holder.laugh.setText(String.valueOf(article.getAttitude0Count()));
                holder.cry.setText(String.valueOf(article.getAttitude1Count()));
                holder.cry.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_down_black_18dp), null, null, null);
                holder.laugh.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(R.drawable.ic_thumb_up_48px), null, null, null);

                mExService.submit(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = OkRestClient.getInstance().post("/article/attitude/add", article.getAttitude());
                        ArticleAttitude articleAttitude = JSON.toJavaObject(jsonObject, ArticleAttitude.class);
                        articleAttitude.setArticle(article.clone());
                        article.setAttitude(articleAttitude);
                    }
                });
            }
        });
    }

    private class ViewHolder extends RecyclerView.ViewHolder {
        ImageView avatar;
        TextView nickname;
        TextView publishTime;
        TextView summary;
        TextView laugh;
        TextView cry;
        TextView comment;

        public ViewHolder(View itemView) {
            super(itemView);
            avatar = (ImageView) itemView.findViewById(R.id.article_avatar);
            nickname = (TextView) itemView.findViewById(R.id.article_nickname);
            publishTime = (TextView) itemView.findViewById(R.id.article_publishTime);
            summary = (TextView) itemView.findViewById(R.id.article_summary);
            laugh = (TextView) itemView.findViewById(R.id.article_good);
            cry = (TextView) itemView.findViewById(R.id.article_bad);
            comment = (TextView) itemView.findViewById(R.id.article_comment);
        }
    }

    private class TextHolder extends ViewHolder {
        TextView text;

        public TextHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.at_text);
        }
    }

    private class PhotoHolder extends ViewHolder {
        ImageView photo;

        public PhotoHolder(View itemView) {
            super(itemView);
            photo = (ImageView) itemView.findViewById(R.id.ap_photo);
        }
    }

    private class AudioHolder extends ViewHolder {
        ImageView audio;
        View pb;

        public AudioHolder(View itemView) {
            super(itemView);
            audio = (ImageView) itemView.findViewById(R.id.audio_play);
            pb = itemView.findViewById(R.id.audio_pb);
        }
    }

    private class VideoHolder extends ViewHolder {
        ProgressBar pb;
        ImageView photo;
        IjkVideoView video;
        ImageView play;

        public VideoHolder(View itemView) {
            super(itemView);
            video = (IjkVideoView) itemView.findViewById(R.id.av_ijkplaer);
            photo = (ImageView) itemView.findViewById(R.id.video_photo);
            pb = (ProgressBar) itemView.findViewById(R.id.pb_load_video);
            play = (ImageView) itemView.findViewById(R.id.video_play);
        }
    }
}